import { useEffect, useState } from 'react';
import { request } from 'umi';
import MultiGrafanaPannel from './components/multiGrafanaPannel';
import SingleGrafanaPannel from './components/singleGrafanaPannel';

const components = {
    "multiGrafanaPannel": MultiGrafanaPannel,
    "singleGrafanaPannel": SingleGrafanaPannel
}

/**
 * 应用观测动态渲染
 * @returns 
 */
const AppObservable = (props) => {
    const [pannelConfig, setPannelConfig] = useState();
    useEffect(() => {
        console.log("useEffect");
        // Get config
        let urlslice = props.match.url.split("/");
        urlslice.splice(2, 0, "v1");
        request(`/resource${urlslice.join("/").toLowerCase()}.json`)
            .then((res) => {
                console.log("setPannelConfig", res);
                setPannelConfig(res);
            })
            .catch((err) => {
                console.log(err);
            });
    }, []);
    if (!pannelConfig) {
        return <></>;
    }
    let pannelType = pannelConfig.type;
    if (!(pannelType in components)) {
        return <></>;
    }
    let Component = components[pannelType];
    return (<Component {...pannelConfig} {...props} />);
};

export default AppObservable;